import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/core/utils/page_visibility_mixin.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/feedback/data/api/feedback_type_enum_api.dart';
import 'package:casdon/modules/feedback/data/model/feedback_record_model.dart';
import 'package:casdon/modules/feedback/providers/feedback_provider.dart';
import 'package:casdon/modules/feedback/ui/screen/feedback_detail_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
@RoutePage()
class FeedbackListScreen extends ConsumerStatefulWidget {
  const FeedbackListScreen({super.key});

  @override
  ConsumerState<FeedbackListScreen> createState() => _FeedbackListScreenState();
}

class _FeedbackListScreenState extends ConsumerState<FeedbackListScreen>
    with PageVisibilityMixin, WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    Future.microtask(() => ref.invalidate(feedbackListProvider));
  }

  @override
  void onPageVisible() {
    ref.invalidate(feedbackListProvider);
  }

  @override
  Widget build(BuildContext context) {
    final feedbackAsync = ref.watch(feedbackListProvider);

    return buildPageVisibilityDetector(
      context,
      Scaffold(
        backgroundColor: context.colorScheme.surface,
        appBar: const CommonAppBar(title: '我的反馈'),
        body: feedbackAsync.when(
          data: (items) => items.isEmpty
              ? _buildEmptyState(context)
              : _buildList(context, ref, items),
          loading: () => const Center(child: CommonLoadingWidget()),
          error: (error, stack) => _buildError(context, ref, error),
        ),
      ),
    );
  }

  Widget _buildList(
    BuildContext context,
    WidgetRef ref,
    List<FeedbackRecordModel> items,
  ) {
    Future<void> _onRefresh() async {
      await ref.refresh(feedbackListProvider.future);
    }

    if (items.isEmpty) {
      return RefreshIndicator(
        onRefresh: _onRefresh,
        child: ListView(
          physics: const AlwaysScrollableScrollPhysics(),
          children: [
            SizedBox(height: 120),
            Center(
              child: Text(
                '暂无反馈记录',
                style: context.textTheme.bodyMedium?.copyWith(
                  color: context.customColorThemeNonNull.textColor2,
                ),
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _onRefresh,
      child: ListView.separated(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
        physics: const AlwaysScrollableScrollPhysics(),
        itemBuilder: (context, index) => _FeedbackRecordCard(
          record: items[index],
          ref: ref,
          onTap: () {
            final record = items[index];
            final infoId =
                record.feedbackInfoId ??
                record.id ??
                record.workOrderType ??
                '';
            if (infoId.isEmpty) {
              ToastUtil.show('暂无法查看该记录详情');
              return;
            }
            Navigator.of(context).push(
              MaterialPageRoute(
                builder: (_) => FeedbackDetailScreen(
                  feedbackInfoId: infoId,
                  title: record.displayTitle,
                ),
              ),
            );
          },
        ),
        separatorBuilder: (_, __) => const SizedBox(height: 12),
        itemCount: items.length,
      ),
    );
  }

  Widget _buildError(BuildContext context, WidgetRef ref, Object error) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '加载失败，请重试',
            style: context.textTheme.bodyMedium?.copyWith(
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
          const SizedBox(height: 12),
          TextButton(
            onPressed: () => ref.refresh(feedbackListProvider),
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image(
            image: Assets.images.emptyData.provider(),
            width: 106.w,
            height: 68.w,
          ),
          SizedBox(height: 16.h),
          Text(
            "暂无数据",
            style: context.textTheme.bodyMedium!.copyWith(
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
        ],
      ),
    );
  }
}

class _FeedbackRecordCard extends StatelessWidget {
  final FeedbackRecordModel record;
  final WidgetRef ref;
  final VoidCallback? onTap;
  const _FeedbackRecordCard({
    required this.record,
    required this.ref,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final feedbackTypesAsync = ref.watch(feedbackTypeListProvider);
    final statusLabel = _statusLabel();
    final statusStyle = _statusStyle(record.status, statusLabel);
    final title = feedbackTypesAsync.when(
      data: (options) => _resolveTitle(options),
      loading: () => record.displayTitle,
      error: (error, stack) => record.displayTitle,
    );
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.04),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Text(
                    title,
                    style: context.textTheme.titleMedium?.copyWith(
                      color: context.customColorThemeNonNull.textColor1,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
                if (statusLabel.isNotEmpty)
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 4,
                    ),
                    decoration: BoxDecoration(
                      color: statusStyle.background,
                      borderRadius: BorderRadius.circular(999),
                    ),
                    child: Text(
                      statusLabel,
                      style: context.textTheme.bodySmall?.copyWith(
                        color: statusStyle.text,
                      ),
                    ),
                  ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              record.createTime ?? '-',
              style: context.textTheme.bodySmall?.copyWith(
                color: context.customColorThemeNonNull.textColor2,
              ),
            ),
            const SizedBox(height: 12),
            Divider(
              height: 1,
              color:
                  context.customColorThemeNonNull.gray2 ??
                  Colors.grey.withOpacity(0.3),
            ),
            const SizedBox(height: 12),
            Text(
              record.title?.isNotEmpty ?? false ? record.title ?? '' : '暂无更多描述',
              style: context.textTheme.bodyMedium?.copyWith(
                color: context.customColorThemeNonNull.textColor2,
              ),
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
    );
  }

  String _statusLabel() {
    final status = record.status?.trim();
    switch (status) {
      case '0':
        return '待处理';
      case '1':
        return '已处理';
      case '2':
        return '已关闭';
      default:
        return record.displayStatus;
    }
  }

  _StatusStyle _statusStyle(String? status, String statusLabel) {
    switch (status) {
      case '0':
        return const _StatusStyle(Color(0xFFFFF2E3), Color(0xFFFF8A00));
      case '1':
        return const _StatusStyle(Color(0xFFE3F9E9), Color(0xFF23A86B));
      case '2':
        return const _StatusStyle(Color(0xFFF7F7F7), Color(0xFF8C8C8C));
      default:
        return const _StatusStyle(Color(0xFFEDEFF2), Color(0xFF5F5F5F));
    }
  }

  String _resolveTitle(List<ResponseFeedbackTypeEnum> options) {
    for (final option in options) {
      final matchesType =
          option.name == record.workOrderType ||
          option.value == record.workOrderType ||
          option.displayName == record.workOrderTypeName ||
          option.name == record.workOrderTypeName ||
          option.value == record.workOrderTypeName;
      if (matchesType) {
        if (option.displayName.isNotEmpty) return option.displayName;
        if (option.name.isNotEmpty) return option.name;
      }
    }
    return record.displayTitle;
  }
}

class _StatusStyle {
  final Color background;
  final Color text;

  const _StatusStyle(this.background, this.text);
}
